import { _once,_list } from '../../common/api/todos'
import { formatDate } from '../../utils/util'
const computedBehavior = require('miniprogram-computed')
const app = getApp()
Component({
  behaviors: [computedBehavior],
  data: {
    userinfo: null,
    navIndex: 0,
    navs: [
      { label:'全部', value: 'Total' },
      { label: '未分配', value: 'NoStaff' },
      { label: '已分配', value: 'IsStaff' },
      { label: '无效', value: 'NoValid' }  
    ],
    keyword: '',
    currentIndex: 0,
    tabs: ['跟进', '来访', '认筹', '认购', '签约'],
    lists: [],
    pageIndexes: [],
    pageSize: 5,
    totalCount: [],
    curTotalCount: [],
    myProject: ''
  },
  computed: {
    totalType () {
      return this.data.navs[this.data.navIndex].value
    },
    stateType() {
      return this.data.tabs[this.data.currentIndex]
    },
    pageIndex() {
      return this.data.pageIndexes[this.data.currentIndex]
    },
    finished() {
      return this.data.curTotalCount.map((item, index) => {
        return this.data.lists.length ? this.data.lists[index].length >= item : false
      })
    },
    showedLists () {
      return this.data.lists.map(item => {
        return item.map(ele => {
          ele.AddTime = formatDate(new Date(ele.AddTime), 'yyyy/MM/dd hh:mm')
          ele.canCall = !ele.CustomerPhone.includes('*')
          return ele
        })
      })
    }
  },
  methods: {
    navChange(e) {
      let navIndex = parseInt(e.detail)
      this.setData({
        navIndex
      }, () => {
        this.initDatas()
        this.totalQuery()
      })
    },
    inputHandler(e) {
      this.setData({
        keyword: e.detail.value
      })
    },
    initDatas() {
      // this.data.lists = []
      this.data.pageIndexes = []
      this.data.totalCount = []
      this.data.curTotalCount = []
      for (let i = 0; i < this.data.tabs.length; i++) {
        // this.data.lists.push([])
        this.data.pageIndexes.push(1)
        this.data.totalCount.push(0)
        this.data.curTotalCount.push(0)
      }
      this.setData({
        // lists: this.data.lists,
        pageIndexes: this.data.pageIndexes,
        totalCount: this.data.totalCount,
        curTotalCount: this.data.curTotalCount
      })
    },
    tabChange(e) {
      let currentIndex = parseInt(e.detail)
      this.setData({
        currentIndex
      })
    },
    swiperChange(e) {
      let currentIndex = parseInt(e.detail.current)
      this.setData({
        currentIndex
      })
    },
    onceQuery () {
      let uid = wx.getStorageSync('uid')
      _once(uid).then(res => {
        if (res.data.IsSuccess) {
          let countObj = res.data.Data
          this.data.navs.forEach(item => {
            item.count = countObj[item.value]
          })
          this.setData({
            navs: this.data.navs
          })
        } else {
          wx.showModal({
            title: '对不起',
            content: res.data.Msg,
            showCancel: false,
            success: r => {
              wx.redirectTo({
                url: '/pages/index/index'
              })
            }
          })
        }
      }).catch(err => {
        console.log(err)
      })
    },
    totalQuery() {
      let uid = wx.getStorageSync('uid')
      app.loading('加载中')
      let queryArr = []
      for (let i = 0; i < this.data.tabs.length; i++) {
        queryArr.push(
          Promise.resolve(
            _list({
              UnionID: uid,
              TotalType: this.data.totalType,
              KeyWord: this.data.keyword,
              StateType: this.data.tabs[i],
              PageIndex: this.data.pageIndexes[i],
              PageSize: this.data.pageSize
            })
          )
        )
      }
      Promise.all(queryArr).then(res => {
        wx.hideLoading()
        if (res[0].data.IsSuccess) {
          let lists = []
          let totalCount = []
          let curTotalCount = []
          let topCount = 0
          for (let i = 0; i < res.length; i++) {
            let arr = res[i].data.Data.CustomerList
            lists.push(arr)
            totalCount.push(res[i].data.Data.TotalCount)
            curTotalCount.push(res[i].data.Data.DataCount)
            topCount += res[i].data.Data.DataCount
          }
          let topc = `navs[${this.data.navIndex}].count`
          let myProject = res[0].data.Data.ProjectName
          this.setData({
            lists,
            totalCount,
            curTotalCount,
            [topc]: topCount,
            myProject
          })
        } else {
          wx.showModal({
            title: '对不起',
            content: res[0].data.Msg,
            showCancel: false,
            success: r => {
              wx.redirectTo({
                url: '/pages/index/index'
              })
            }
          })
        }
        wx.stopPullDownRefresh()
      }).catch(err => {
        wx.stopPullDownRefresh()
        console.log(err)
        wx.hideLoading()
        wx.showModal({
          title: '对不起',
          content: JSON.stringify(err) || '网络错误，请稍后再试',
          showCancel: false
        })
      })
    },
    concatList() {
      let uid = wx.getStorageSync('uid')
      let currentIndex = this.data.currentIndex
      let pageIndex = this.data.pageIndex
      _list({
        UnionID: uid,
        KeyWord: this.data.keyword,
        TotalType: this.data.totalType,
        StateType: this.data.stateType,
        PageIndex: pageIndex,
        PageSize: this.data.pageSize
      }).then(res => {
        let list = res.data.Data.CustomerList
        this.data.lists[currentIndex] = this.data.lists[currentIndex].concat(list)
        let str = `lists[${currentIndex}]`
        this.setData({
          [str]: this.data.lists[currentIndex]
        })
      }).catch(err => {
        console.log(err)
        wx.showModal({
          title: '对不起',
          content: JSON.stringify(err) || '网络错误，请稍后再试',
          showCancel: false
        })
      })
    },
    search() {
      this.initDatas()
      this.totalQuery()
    },
    onReachLower() {
      let currentIndex = this.data.currentIndex
      if (this.data.finished[currentIndex]) {
        return
      }
      this.data.pageIndexes[currentIndex] += 1
      let pageindex = `pageIndexes[${currentIndex}]`
      this.setData({
        [pageindex]: this.data.pageIndexes[currentIndex]
      }, () => {
        this.concatList()
      })
    },
    onLoad(options) {
      this.onceQuery()
    },
    onReady() { },
    onShow() {
      this.initDatas()
      app.launch().then(res => {
        this.setData({
          userinfo: res
        })
        this.totalQuery()
      }).catch(err => {
        console.log(err)
        if (err === '用户未注册') {
          wx.showModal({
            title: '对不起',
            content: '您还未注册',
            showCancel: false,
            success: r => {
              if (r.confirm) {
                wx.redirectTo({
                  url: '/pages/index/index'
                })
              }
            }
          })
        }
      })
    },
    onPullDownRefresh() {
      this.initDatas()
      this.totalQuery()
    },
    onShareAppMessage() {
      return app.shareInfo
    }
  }
})